package com.test.ai.service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 8/20/25 2:53 PM
 * @modifiedBy:
 * @version: 1.0
 */
@Service
public class QwenChatService {
  private final ChatClient chatClient;
  private final MessageChatMemoryAdvisor messageChatMemoryAdvisor;

  public QwenChatService(
      @Qualifier("openAiChatClient") ChatClient chatClient,
      MessageChatMemoryAdvisor messageChatMemoryAdvisor) {
    this.chatClient = chatClient;
    this.messageChatMemoryAdvisor = messageChatMemoryAdvisor;
  }

  /**
   * Generate response flux.
   *
   * @param userInput the user input
   * @return the flux
   */
  public Flux<String> generateResponse(String userInput, String conversationId) {
    // 系统提示词（可选）
    SystemPromptTemplate systemPromptTemplate =
        new SystemPromptTemplate(
            """
            你是一个专业的AI助手，请用中文简洁准确的回答用户问题。
            当前时间: {time}
            """);
    Message systemMessage =
        systemPromptTemplate.createMessage(Map.of("time", LocalDateTime.now().toString()));
    // 用户消息
    UserMessage userMessage = new UserMessage(userInput);
    // 构建prompt
    Prompt prompt = new Prompt(List.of(systemMessage, userMessage));
    // 调用大模型进行响应
    return chatClient
        .prompt(prompt)
        .advisors(
            advisorSpec ->
                advisorSpec
                    .param(
                        MessageChatMemoryAdvisor.DEFAULT_CHAT_MEMORY_CONVERSATION_ID,
                        conversationId)
                    .param(MessageChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)
                    .advisors(messageChatMemoryAdvisor))
        .stream()
        .content();
  }
}
